#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "stpool.h"
#include "msglog.h"

#define ThreadsMax 16
#define ThreadsMin 8
#define WKLDS 		100

typedef int	THR_PARA_T;

/**
  * @brief  事务处理程序.
  * @Notes  stpool线程池模型下的事务处理程序固定格式.
  * @param  ptsk, stpool线程传入参数
  * @retval None.
  */
void MYAPP_TASK(struct sttask *ptsk)
{
	THR_PARA_T* tppara = (THR_PARA_T*)(ptsk->task_arg);
	printf("thread parameter: %d\n", *tppara);
	sleep(1);
}

int main(int argc, char* argv[])
{
	/* 线程池初始化 */
	stpool_t *thrpool;
	long eCAPs;

	// 设置stpool库的报错级别为: LOG_ERR，只显示严重错误 
    MSG_log_set_level(LOG_ERR);
    eCAPs = eCAP_F_DYNAMIC|eCAP_F_SUSPEND|eCAP_F_THROTTLE|eCAP_F_ROUTINE|
			eCAP_F_DISABLEQ|eCAP_F_PRIORITY|eCAP_F_WAIT_ALL;
	
	/* 初始化线程池 */
	thrpool = stpool_create("Win32Sample", eCAPs, ThreadsMax, ThreadsMin, 0, 1);
	if(!thrpool){ 
		fprintf(stderr, "ThreadPool/> {ERROR} Application-Workers thread pool initialize failed!\n");
	}
	else{ 
		fprintf(stderr, "%s\n", stpool_stat_print(thrpool));
	}

	// >>>>>>>>>>> stpool线程池添加工作负载 >>>>>>>>>>>
	// 事务处理线程所用到的变量，通过函数的第5个参数传入
			THR_PARA_T tppara[WKLDS]; 
			for(int i = 0; i < WKLDS; i++){
				tppara[i] = i+1;
				stpool_add_routine(thrpool, "Win32Sample", MYAPP_TASK, NULL, &tppara[i], NULL);
			}

	// Wait for all workloads' tasks being done completely
			stpool_wait_all(thrpool, -1);

	/* 释放线程池资源 */
	if(thrpool != NULL){
		stpool_release(thrpool);
		fprintf(stderr, "ThreadPool/> {INFO} Current Thread-pool release.\n");
	}else{
		fprintf(stderr, "ThreadPool/> {INFO} Current Thread-pool is null.\n");
	}
}